import { useUserStore } from '@/store/user'
import { useRouteStore } from '@/store/route'
import { fetchRoutes } from '@/api/route'

// 路由白名单（不需要权限检查的路由）
const whiteList = [
  '/pages/login/index',
  '/pages/login/register',
  '/pages/404/index',
  '*'
]

// 初始化路由
export async function initRoutes() {
  const routeStore = useRouteStore()

  if (routeStore.isRoutesExpired) {
    try {
      const routes = await fetchRoutes()
      routeStore.setRoutes(routes)
    } catch (error) {
      console.error('获取路由失败:', error)
      if (!routeStore.routes.length) {
        uni.showToast({
          title: '系统初始化失败',
          icon: 'none'
        })
        return false
      }
    }
  }
  return true
}

// 路由守卫
export function setupRouterGuard() {
  const routerGuard = async (to) => {
    const userStore = useUserStore()
    const routeStore = useRouteStore()

    console.log('路由守卫触发', to.url)
    // 白名单直接放行
    if (whiteList.includes(to.url) || whiteList.includes('*')) {
      return true
    }

    // 确保路由已初始化
    if (!(await initRoutes())) return false

    // 查找目标路由配置
    const route = routeStore.routes.find(route => route.path === to.url)

    // 未配置的路由跳转到404
    if (!route) {
      uni.redirectTo({ url: '/pages/404/index' })
      return false
    }

    // 需要登录但未登录
    if (route.requireAuth && !userStore.token) {
      uni.redirectTo({ url: '/pages/login/index' })
      return false
    }

    // 需要特定角色权限
    if (route.roles?.length > 0) {
      const hasRole = route.roles.some(role => userStore.roles.includes(role))
      if (!hasRole) {
        // 无权限时跳转到404而不是noauth页面
        uni.redirectTo({ url: '/pages/404/index' })
        return false
      }
    }

    return true
  }

  // 注册全局路由守卫
  uni.addInterceptor('navigateTo', {
    invoke: async (args) => {
      const canAccess = await routerGuard({ url: args.url })
      return canAccess ? args : false
    }
  })

  uni.addInterceptor('redirectTo', {
    invoke: async (args) => {
      const canAccess = await routerGuard({ url: args.url })
      return canAccess ? args : false
    }
  })

  uni.addInterceptor('reLaunch', {
    invoke: async (args) => {
      const canAccess = await routerGuard({ url: args.url })
      return canAccess ? args : false
    }
  })
}